package cn.myframe.utils.aop;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import cn.myframe.entity.sys.CheckData;
import cn.myframe.service.sys.SysUtilsService;
import cn.myframe.utils.BaseDataUtils;
import cn.myframe.utils.core.R;
import cn.myframe.utils.annotation.CheckDelete;


/**
 * 删除数据前，判断是否被关联
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017年3月8日 上午11:07:35
 */
@Aspect
@Component
public class CheckDeleteAspect {
	
	
	@Autowired
	private SysUtilsService sysUtilsService;
	
	@Pointcut("@annotation(cn.myframe.utils.annotation.CheckDelete)")
	public void logPointCut() { 
		
	}
	
	@Around("logPointCut()")
	public Object checkDelete(ProceedingJoinPoint  joinPoint) throws Throwable {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		CheckDelete associateData = method.getAnnotation(CheckDelete.class);
		//请求的参数
		Object[] args = joinPoint.getArgs();
		List<Object> ids = JSON.parseArray(JSON.toJSONString(args[0]), Object.class);
		String value = associateData.value();
		if(StringUtils.isNotEmpty(value)){
			String[] datas = value.split(",");
			for(String deleteData : datas){
				CheckData data = AssociateData.associateData.get(deleteData);
				data.setIds(ids);
				List<Map<String,Object>> list = null;
				if(data.getType().equals("1")){
					 list = sysUtilsService.checkDeleteData(data);
				}else if(data.getType().equals("2")){
					list = sysUtilsService.checkMidDeleteData(data);
				}
				else if(data.getType().equals("3")){//黑名单
					list = sysUtilsService.checkMidDeleteData(data);
				}
				if(list!=null&&list.size()>0){
					Map<String,Object> map = list.get(0);
					String name = map.get("name") == null ? "" : String.valueOf(map.get("name"));
					return R.error(data.getAssDesc()+"["+map.get("assName")+"]"+BaseDataUtils.getSysterm("be")+
							data.getDesc()+"["+name+"]"+BaseDataUtils.getSysterm("checkAssociateDelete"));
				}
			}
		}
		Object o = joinPoint.proceed();
		return o;
	}
	
	
}


